﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace For_FS_2013_1_User
{
    class Connector
    {
        private List<UserConnection> connections;
        private List<int> availablePorts;
        private Thread recon;

        public Connector()
        {
            connections = new List<UserConnection>();
            availablePorts = new List<int>();
            CreatePorts();
            recon = new Thread(Reconnector);
            recon.Start();
        }

        private void CreatePorts()
        {
            for (int i = 14; i <= 120; i = i + 2)
                availablePorts.Add(i);
            availablePorts.Remove(80);
            availablePorts.Remove(8080);
        }

        private void Reconnector()
        {
            while (true)
            {
                if (Program.defCon.clientAvailable)
                    lock (Program.defCon)
                    {
                        int port = availablePorts[0];
                        availablePorts.Remove(port);
                        ConnectNewUser(port);
                        Program.defCon.Send("reconnect "+port); //////////
                        Thread.Sleep(500);
                        Program.defCon.Disconnect();
                    }
            }
        }

        public void ConnectNewUser(int port)
        {
            connections.Add(new UserConnection(port));
        }

        public void DisconnectUser(UserConnection con)
        {
            availablePorts.Add(con.GetPort());
            connections.Remove(con);
            availablePorts.Sort();
        }

        public List<string> ShowUsers()
        {
            List<string> res = new List<string>();
            if (connections.Count == 0)
                res.Add("There is no any user, connected to the system!!!");
            foreach (UserConnection c in connections)
                //Console.WriteLine(c.GetUserLogin()+"     "+c.GetPort());
                res.Add("User->"+c.GetPort());
            return res;
        }
    }
}
